package com.yu1996.gulimall.product.exception;

import com.yu1996.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * Description: 统一异常处理类
 * Date: 2021/8/25
 * Author: yu
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.yu1996.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {
    private Map<String, String> errMap = new HashMap<>();

    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public R handleVaildException(MethodArgumentNotValidException e) {
        log.error("数据出现{}异常，异常类型{}", e.getMessage(), e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getFieldErrors().forEach((fieldError -> {
            errMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        }));
        return R.error(400,"参数错误").put("data",errMap);
    }
}
